﻿using AutoMapper;
using Fake_Shop_WebApi.Dtos;
using Fake_Shop_WebApi.Helper;
using Fake_Shop_WebApi.Models;
using Fake_Shop_WebApi.Services;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Claims;
using System.Threading.Tasks;

namespace Fake_Shop_WebApi.Controllers
{
    [Authorize]
    [Route("api/ShoppingCart")]
    public class ShoppingCartControllers:ControllerBase
    {
        private readonly IHttpContextAccessor _httpContextAccessor;
        private readonly ITouristRouteRepository _touristRouteRepository;
        private readonly IMapper _mapper;
        public ShoppingCartControllers(IHttpContextAccessor httpContextAccessor,
            ITouristRouteRepository touristRouteRepository,
            IMapper mapper
            )
        {
            _httpContextAccessor = httpContextAccessor;
            _touristRouteRepository = touristRouteRepository;
            _mapper = mapper;
        }

        [HttpGet]
        [Authorize(AuthenticationSchemes = "Bearer")]
        public async Task<IActionResult> GetShoppingCart()
        {
            //获取用户数据
            var UserId = _httpContextAccessor.HttpContext.User.FindFirst(ClaimTypes.NameIdentifier).Value;
            //使用userid获取购物车
            var ShoppingCart = await _touristRouteRepository.GetShoppingCartByUserIdAsync(UserId);
            return Ok(_mapper.Map<ShppingCartDto>(ShoppingCart));

        }
        [HttpPost("items")]
        [Authorize(AuthenticationSchemes = "Bearer")]
        public async Task<IActionResult> AddShoppingCart([FromBody] AddShoppingItemDto addShoppingItemDto)
        {
            //获取用户
            var UserId = _httpContextAccessor.HttpContext.User.FindFirst(ClaimTypes.NameIdentifier).Value;
            //使用USerId 获取购物车
            var ShoppingCart = await _touristRouteRepository.GetShoppingCartByUserIdAsync(UserId);
           
            var touristRoute  = await _touristRouteRepository.GetTouristRouteAsync(addShoppingItemDto.TouristRouteId);
            if (touristRoute == null)
            {
                return NotFound("找不到旅游路线");
            }

            var lineItem = new LineItem()
            {
                TourisTouteId = addShoppingItemDto.TouristRouteId,
                ShoppingCartId = ShoppingCart.Id,
                OriginalPrice = touristRoute.OriginalPrice,
                DiscountPresent = touristRoute.DiscountPresent
            };
            await _touristRouteRepository.AddShoppingCartItem(lineItem);
            await _touristRouteRepository.SaveAsync();
            return Ok(_mapper.Map<ShoppingCart>(ShoppingCart));
        }
        [HttpDelete("items/{itemsId}")]
        [Authorize(AuthenticationSchemes = "Bearer")]
        public async Task<IActionResult> DeleteShopingItem([FromRoute]int itemsId)
        {
            //获取用户
            var lineItem = await _touristRouteRepository.GetShoppingCartItemAsync(itemsId);
            if(lineItem == null)
            {
                return NotFound("购物车商品找不到");
            }
            //删除，并保存
             _touristRouteRepository.DeleteShopingCart(lineItem);
            await _touristRouteRepository.SaveAsync();
            return NoContent();
        }
        [HttpDelete("items/({itemIDs})")]
        [Authorize(AuthenticationSchemes = "Bearer")]
        public async Task<IActionResult> DeleteShoppingList(
            [ModelBinder(BinderType = typeof(ArrayModelBinder))]
            [FromBody] IEnumerable<int> itemIds
            )
        {
            var lineItem = await _touristRouteRepository.GeshoppingCartsByIdListAsync(itemIds);

            _touristRouteRepository.DeleteShoppingCartItems(lineItem);
           await _touristRouteRepository.SaveAsync();
            return NoContent();
        }
        [HttpPost("checkout")]
       [Authorize(AuthenticationSchemes = "Bearer")]
       public async Task<IActionResult> AddOrder()
        {
            //获取用户
            var UserId = _httpContextAccessor.HttpContext.User.FindFirst(ClaimTypes.NameIdentifier).Value;
            //使用USerId 获取购物车
            var ShoppingCart = await _touristRouteRepository.GetShoppingCartByUserIdAsync(UserId);

            var order = new Order()
            {
                Id = Guid.NewGuid(),
                UserId = UserId,
                StateEnum = OrderStateEnum.Pending,
                OrderItem = ShoppingCart.ShoppingCartItem,
                CreateDateUTC = DateTime.UtcNow
            };
            //清空购物车
            ShoppingCart.ShoppingCartItem = null;
            await _touristRouteRepository.AddOrderAsync(order);
            await _touristRouteRepository.SaveAsync();

            return Ok(_mapper.Map<OrderDto>(order));

        }
        

    }
}
